/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * This file is part of retabel.
 *
 * Copyright (c) 2011 by individual contributors as indicated by the
 * @author tags. See the copyright.txt file in the distribution
 * for a full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */

package org.retabel.backendbean;

import org.apache.http.HttpResponse;
import org.retabel.jsf.PagedListDataModel;
import org.retabel.jsf.ReportDesignUriBuilder;
import org.retabel.ui.ReportDesignPackageUI;
import org.retabel.ui.ReportDesignUI;
import org.retabel.util.HttpDeleteClientRequestRunner;
import org.retabel.util.HttpGetClientRequestRunner;
import org.retabel.util.JaxbUtils;
import org.retabel.util.LogLines;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xsd.reportdesignpackage.ReportDesign;
import xsd.reportdesignpackages.ReportDesignPackage;
import xsd.reportdesignpackages.ReportDesignPackages;

import javax.enterprise.context.RequestScoped;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import javax.faces.model.DataModel;
import javax.inject.Named;
import java.util.ArrayList;
import java.util.List;

@ManagedBean
@RequestScoped
@Named
public class ReportDesignListBean extends PagedListBean {

    // constants

    private static final Logger log = LoggerFactory.getLogger(ReportDesignListBean.class);

    // private fields

    private List<ReportDesignUI> reportDesigns = new ArrayList<>();

    private LogLines logLines = new LogLines(log);

    // private functions

    private ReportDesignPackages getPage(int first, int maxRows) throws Exception {
        // we don't want any log lines, use null as log lines parameter therefore
        return new HttpGetClientRequestRunner<ReportDesignPackages>(null) {
            @Override
            protected ReportDesignPackages onSuccess(HttpResponse response, LogLines logLines) throws Exception {
                return JaxbUtils.unmarshal(ReportDesignUriBuilder.getReportDesignPackagesXmlSchemaURI().toURL(),
                                           response.getEntity().getContent(), ReportDesignPackages.class);
            }

            @Override
            protected void onFailure(HttpResponse response, LogLines logLines) throws Exception {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                                                                    "request failed",
                                                                                    response.getStatusLine().toString()));
            }
        }.run(ReportDesignUriBuilder.getReportDesignPackagesURI(first, maxRows));
    }

    // protected methods

    @Override
    protected DataModel getDataModel() throws Exception {
        ReportDesignPackages reportDesignPackagesPage = getPage(getUiData().getFirst(), getUiData().getRows());

        List<ReportDesignPackageUI> reportDesignPackageUIs = new ArrayList<>();
        int count = 0;

        if (reportDesignPackagesPage != null && reportDesignPackagesPage.getList() != null) {
            count = reportDesignPackagesPage.getCount();

            for (ReportDesignPackage reportDesignPackage : reportDesignPackagesPage.getList().getReportDesignPackage()) {
                ReportDesignPackageUI reportDesignpackageUI = new ReportDesignPackageUI();

                reportDesignpackageUI.setPackageName(reportDesignPackage.getName());
                reportDesignpackageUI.setVersion(reportDesignPackage.getVersion());

                reportDesignPackageUIs.add(reportDesignpackageUI);
            }
        }

        return new PagedListDataModel(reportDesignPackageUIs, count, getUiData().getRows());
    }

    // public functions

    @Override
    public void delete() throws Exception {
        ReportDesignPackageUI reportDesignPackageUI = (ReportDesignPackageUI) getUiData().getRowData();

        new HttpDeleteClientRequestRunner<Boolean>(logLines) {
            @Override
            protected Boolean onSuccess(HttpResponse response, LogLines logLines) throws Exception {
                logLines.log(getResponseContentAsString(response));

                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,
                                                                                    "report design package deleted successfully",
                                                                                    response.getStatusLine().toString()));

                return Boolean.TRUE;
            }

            @Override
            protected void onFailure(HttpResponse response, LogLines logLines) throws Exception {
                logLines.log(getResponseContentAsString(response));

                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                                                                    "delete report design package failed",
                                                                                    response.getStatusLine().toString()));
            }
        }.run(ReportDesignUriBuilder.getReportPackageDeleteURI(reportDesignPackageUI.getPackageName(),
                                                               reportDesignPackageUI.getVersion()));
    }

    public void designPackage() throws Exception {
        ReportDesignPackageUI reportDesignPackageUI = (ReportDesignPackageUI) getUiData().getRowData();

        xsd.reportdesignpackage.ReportDesignPackage reportDesignPackage =
            new HttpGetClientRequestRunner<xsd.reportdesignpackage.ReportDesignPackage>(logLines) {
                @Override
                protected xsd.reportdesignpackage.ReportDesignPackage onSuccess(HttpResponse response, LogLines logLines)
                    throws Exception {
                    return JaxbUtils.unmarshal(ReportDesignUriBuilder.getReportDesignPackageXmlSchemaURI().toURL(),
                                               response.getEntity().getContent(),
                                               xsd.reportdesignpackage.ReportDesignPackage.class);
                }

                @Override
                protected void onFailure(HttpResponse response, LogLines logLines) throws Exception {
                    FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                                                                        "request failed",
                                                                                        response.getStatusLine().toString()));
                }
            }.run(ReportDesignUriBuilder.getReportDesignPackageURI(reportDesignPackageUI.getPackageName(),
                                                                   reportDesignPackageUI.getVersion()));

        for (ReportDesign reportDesign : reportDesignPackage.getReportDesign()) {
            ReportDesignUI reportDesignUI = new ReportDesignUI();
            reportDesignUI.setPackageName(reportDesignPackage.getName());
            reportDesignUI.setVersion(reportDesignPackage.getVersion());
            reportDesignUI.setDesignName(reportDesign.getName());
            reportDesignUI.setDownloadUri(ReportDesignUriBuilder.getReportDesignDownloadURI(reportDesignPackage.getName(),
                                                                                            reportDesignPackage.getVersion(),
                                                                                            reportDesign.getName()));

            reportDesigns.add(reportDesignUI);
        }
    }

    /**
     * Gets the reportDesigns.
     *
     * @return The reportDesigns value.
     */
    public List<ReportDesignUI> getReportDesigns() {
        return reportDesigns;
    }
}